var canvas;
var context;
var isDrawing = false;       //表示可以正在画图
var isOkDrawing = false;     //表示进入画图的模式
var isSelecting = false;     //表示进入选择图形模式
var isDragging = false;      //表示正在拖拽图形
var isover = false;
var oldcolor; 			     //用于记录上一次的颜色
var oldfillcolor;            //用于记录上一次的填充颜色
var oldpathwidth;            //用于记录之前的画笔宽度
var previousSelectedform;    //用于记录当前选择的图形
var previousnum;             //用于记录当前选中图形的下标

var circle;                  //圆形的中间变量
var rectangle;               //矩形的中间变量
var line;                    //线段的中间变量
var wordvalue;               //用于记录输入的文本内容
var word;                    //文本的中间变量

var num = 0;                 //用于调试查看图形的个数

//起始点，终止点
var startx;
var starty;
var endx;
var endy;
//用于绘制矩形
var maxendx;
var maxendy;
var minendx;
var minendy;
//用于绘制圆形
var maxradius = 0;
//用于绘制线段
var bendx = 0;
var bendy = 0;
//用于绘制文本
var wordvalue;
var wordfond;
var wordx;
var wordy;
var width;
var fillcolor;
var strokecolor;
var shixin;

//记录画什么图形的变量
// 1表示矩形，2表示圆形，3表示线段, 4表示文字
var shape; 

//生成各种图形对象的函数
//圆形
function Circle(x,y,radius,linecolor,linewidth,color) 
{
	this.x = x;
	this.y = y;
	this.radius = radius;
	this.linecolor = linecolor;
	this.linewidth = linewidth;
	this.color = color;
	this.isSelected = false;
}
var circles = [];
//矩形
function Rectangle (sx,sy,ex,ey,linecolor,linewidth,color) 
{
	this.sx = sx;
	this.sy = sy;
	this.ex = ex;
	this.ey = ey;
	this.linecolor = linecolor;
	this.linewidth = linewidth;
	this.color = color;
	this.isSelected = false;
}
var rectangles = [];
//线段
function Line (sx,sy,ex,ey,linecolor,linewidth) 
{
	this.sx = sx;
	this.sy = sy;
	this.ex = ex;
	this.ey = ey;
	this.linecolor = linecolor;
	this.linewidth = linewidth;
	this.isSelected = false;
}
var lines = [];
//文字
function Word (value,wfond,x,y,width,fillcolor,strokecolor,shixin,wordwidth)
{
	this.value = value;
	this.wfond = wfond;
	this.x = x;
	this.y = y;
	this.wordwidth = wordwidth;
	this.width = width;
	this.fillcolor = fillcolor;
	this.strokecolor = strokecolor;
	this.shixin = shixin;
	this.isSelected = false;
}
var words = [];

//页面启动执行一些初始化措施
window.onload = function () 
{
	//canvas自适应宽高
	var cdiv = document.getElementById('content');
	//获取父容器的长宽
	// alert(cdiv.offsetWidth);
	// alert(cdiv.offsetHeight);
	canvas = document.getElementById('myCanvas');
	context = canvas.getContext("2d");
	// alert(can.height);
	// alert(can.width);
	canvas.height = cdiv.offsetHeight;
	canvas.width = cdiv.offsetWidth;

	wordvalue = document.getElementById('word2');

	//设置初始值
	context.strokeStyle = '#FF0000';
	context.fillStyle = '#FF0000';
	context.globalAlpha = 0.85;
	oldcolor = '#FF0000';
	oldfillcolor = '#FF0000';
	oldpathwidth = 1;
	isOkDrawing = true;
	isSelecting = false;
	shape=3;

	wordfond = "normal lighter 50px cursive";
	wordx = canvas.width/2;
	wordy = canvas.height/2;
	wordwidth = oldpathwidth;
	width = 200;
	fillcolor = context.fillStyle;
	strokecolor = context.strokeStyle;
	shixin = 1; //一代表是实心文字 二代表是空心文字

	canvas.onmousedown = startDrawing;
	canvas.onmouseup = addDrawing;
	canvas.onmouseout = stopDrawing;
	canvas.onmousemove = draw;	
}

function startDrawing (e)
{
	if(isOkDrawing)
		isDrawing = true;
	isover = true;
	startx = e.pageX - canvas.offsetLeft;
	starty = e.pageY - canvas.offsetTop;
	// if(shape==3)//画圆形有这个会多一条线
	// {
	// 	context.moveTo(startx, starty);
	// }

	minendx = startx;
	minendy = starty;
	maxendx = startx;
	maxendy = starty;
	
	maxradius = 0;

	bendx = startx;
	bendy = starty;
}

function addDrawing () 
{
	isDrawing = false;

	//很诡异，这两个if换一下
	//如果先画矩形就会导致画圆形之前的矩形莫名消失
	//解释为如果使用的变量没有意义的话，这一次的操作就结束

	if(shape==1)
	{
		//长与宽超过三十个像素才能被加入矩形集
		if(rectangle.ex - rectangle.sx > 30 && rectangle.ey - rectangle.sy > 30) 	   
		{       						   
			rectangles.push(rectangle);
		}
	}
	console.log("矩形的数量");
	console.log(rectangles.length);
	
	if(shape==2)
	{
		//半径超过三十个像素才能被加入圆形集
		if(circle.radius > 30)
		{
			circles.push(circle);
		}
	}
	console.log("圆形的数量");
	console.log(circles.length);
	
	if(shape==3)
	{
		//长度超过三十个像素才能被加入线段集
		if(((line.ex - line.sx > 50 || line.ex - line.sx < -50))||(line.ey - line.sy > 50 || line.ey - line.sy < -50))
		{
			lines.push(line);			 
		}
	}
	console.log("线段的数量");
	console.log(lines.length);

	isDrawing = true;
	drawAll();
}

function stopDrawing (e) 
{
	isDrawing = false;
	//这种方法不太对
	// if(isover==true)
	// {
	// 	var endx = e.pageX - canvas.offsetLeft;
	// 	var endy = e.pageY - canvas.offsetTop;
	// 	if(shape==1) //绘制矩形
	// 	{
	// 		context.rect(startx,starty,endx-startx,endy-starty);
	// 	}
	// 	else if (shape==2) //绘制圆形
	// 	{
	// 		var radius = Math.sqrt((endx-startx)*(endx-startx)+(endy - starty)*(endy - starty));
	// 		context.arc(startx,starty,radius,0,2*Math.PI);
	// 	}
	// 	else if (shape==3) //绘制线段
	// 	{
	// 		context.lineTo(endx,endy);
	// 	}
	// 	context.stroke();
	// }
	// isover = false;
}

function draw (e)
{
	if(isDrawing==true)
	{
		console.log('打印图形了');
		endx = e.pageX - canvas.offsetLeft;
		endy = e.pageY - canvas.offsetTop;
		context.strokeStyle = oldcolor;
		context.lineWidth = oldpathwidth;

		if(shape==1 && isOkDrawing) //绘制矩形 //进入绘画模式
		{
			if(maxendx < endx)
			{
				maxendx = endx;
			}
			if(maxendy < endy)
			{
				maxendy = endy;
			}
			if(minendx > endx)
			{
				minendx = endx;
			}
			if(minendy > endy)
			{
				minendy = endy;
			}
			//设置误差,可以使画矩形的时候不重复回去
			var wuca = 0;
			if(endx > startx)
			{
				if(maxendx > endx + wuca)
				{
					isDrawing = false;
				}
			}
			if(endy > starty)
			{
				if(maxendy > endy + wuca)
				{
					isDrawing = false;
				}
			}
			if(endx < startx)
			{
				if(minendx < endx - wuca)
				{
					isDrawing = false;
				}
			}
			if(endy < starty)
			{
				if(minendy < endy - wuca)
				{
					isDrawing = false;
				}
			}
			var minx;
			var miny;
			var maxx;
			var maxy;
			if(startx > endx)
			{
				minx = endx;
				maxx = startx;
			}
			else
			{
				minx = startx;
				maxx = endx;
			}
			if(starty > endy)
			{
				miny = endy;
				maxy = starty;
			}
			else
			{
				miny = starty;
				maxy = endy;
			}
			rectangle = new Rectangle(minx,miny,maxx,maxy,context.strokeStyle,context.lineWidth,context.fillStyle);

			context.beginPath();
			//context.fillStyle = "rgba(238,238,238,1)";    //用填充方法轻松解决内部很多线的问题
			context.fillStyle = oldfillcolor;
			//context.globalAlpha = 0.8;
			context.rect(startx,starty,endx-startx,endy-starty);
			context.fill();
			context.stroke();
			//context.clearRect(startx,starty,endx-startx,endy-starty);
			context.closePath();
			// context.clearRect(endx,endy,maxendx - endx,maxendy - endy);
			// context.clearRect(endx,starty,maxendx - endx,endy-starty);
			// context.clearRect(startx,endy,endx - startx,maxendy-endy);

		}
		else if (shape==2 && isOkDrawing) //绘制圆形  //进入绘画模式
		{
			var radius = Math.sqrt((endx-startx)*(endx-startx)+(endy - starty)*(endy - starty));
			if(maxradius < radius)
			{
				maxradius = radius;
			}
			if(maxradius > radius)
			{
				isDrawing = false;
			}
			circle = new Circle(startx,starty,radius,context.strokeStyle,context.lineWidth,context.fillStyle);
			
			context.beginPath();
			context.arc(circle.x, circle.y, circle.radius, 0, Math.PI*2);
			context.fillStyle = circle.color;
			context.strokeStyle = circle.linecolor;
			context.lineWidth = circle.linewidth;
			context.fill();
			context.stroke();
			context.closePath();

			// context.beginPath();
			// //context.fillStyle = "rgba(238,238,238,1)";    //用填充方法轻松解决内部很多线的问题
			// context.fillStyle = oldfillcolor;
			// context.globalAlpha = 0.8;
			// context.arc(startx,starty,radius,0,2*Math.PI);
			// context.fill();
			// context.stroke();
			
			// //context.arc(startx,starty,radius-10,0,2*Math.PI);
			// //context.stroke();
			// context.closePath();
		}
		else if (shape==3 && isOkDrawing) //绘制线段 //进入绘画模式
		{
			line = new Line(startx,starty,endx,endy,context.strokeStyle,context.lineWidth);
			
			//把之前的一条线去掉
			context.beginPath();
			context.strokeStyle = '#EEEEEE';
			context.lineWidth = context.lineWidth;
			context.moveTo(startx,starty);
			context.lineTo(bendx,bendy);
			context.stroke();
			context.closePath();

			bendx = endx;
			bendy = endy;

			context.beginPath();
			context.strokeStyle = oldcolor;
			context.lineWidth = oldpathwidth;
			context.moveTo(startx,starty);
			context.lineTo(endx,endy);
			context.stroke();
			context.closePath();
		}
	}
}

//将保存的图形都绘制出来
function drawAll () 
{
	if(isDrawing)
	{
		//绘图之前将页面清空
		context.clearRect(0,0,canvas.width,canvas.height);
		if(shape)
		{
			console.log("正在绘制圆形");
			for(var i=0; i<circles.length; i++)
			{
				context.beginPath();
				context.arc(circles[i].x, circles[i].y, circles[i].radius, 0, Math.PI*2);

				context.fillStyle = circles[i].color;
				context.strokeStyle = circles[i].linecolor;
				context.lineWidth = circles[i].linewidth;

				if (circles[i].isSelected) 
				{
					context.lineWidth = context.lineWidth+5;
				}
				context.fill();
				context.stroke(); 
				context.closePath();
			}
		}
		if(shape)
		{
			console.log("正在绘制矩形");
			for(var i=0; i<rectangles.length; i++)
			{
				context.beginPath();
				context.rect(rectangles[i].sx,rectangles[i].sy,rectangles[i].ex - rectangles[i].sx,rectangles[i].ey - rectangles[i].sy);

				context.fillStyle = rectangles[i].color;
				context.strokeStyle = rectangles[i].linecolor;
				context.lineWidth = rectangles[i].linewidth;

				if (rectangles[i].isSelected) 
				{
					context.lineWidth = context.lineWidth+5;
				}
				context.fill();
				context.stroke();
				context.closePath();
			}
		}
		if(shape)
		{
			console.log("正在绘制线段");
			for(var i=0; i<lines.length; i++)
			{
				context.beginPath();
				context.moveTo(lines[i].sx, lines[i].sy);
				context.lineTo(lines[i].ex, lines[i].ey);
				context.strokeStyle = lines[i].linecolor;
				context.lineWidth = lines[i].linewidth;
				if (lines[i].isSelected) 
				{
					context.lineWidth = context.lineWidth+5;
				}
				context.stroke();
				context.closePath();
			}
		}
		if(shape)
		{
			console.log("正在绘制文本");
			for(var i=0; i<words.length; i++)
			{
				console.log(words[i]);
				context.font = words[i].wfond;
				context.fillStyle = words[i].fillcolor;
				context.strokeStyle = words[i].strokecolor;
				context.lineWidth = words[i].wordwidth;          //还有待继续调整字体
				if(words[i].isSelected)
				{
					context.fillStyle = "#FF8800";
					context.strokeStyle = "#FF8800";
				}
				if(words[i].shixin==1)
				{
					context.fillText(words[i].value,words[i].x,words[i].y,words[i].width);
				}
				if(words[i].shixin==2)
				{
					context.strokeText(words[i].value,words[i].x,words[i].y,words[i].width);
				}
				context.fillStyle = words[i].fillcolor;
				context.strokeStyle = words[i].strokecolor;
			}
		}
		isDrawing = false;
	}
}

//添加文字信息
function drawword()
{	
	if(shape==4&&isOkDrawing)
	{
		//文字信息每次都需要重新输入
		//word = document.getElementById('word2');
		console.log("wordvalue.value");console.log(wordvalue.value);
		if(isOkDrawing)
		{
			word = new Word(wordvalue.value,wordfond,wordx,wordy,width,context.fillStyle,context.strokeStyle,shixin,context.lineWidth);
			words.push(word);
			isDrawing = true;
			drawAll();
		}
		/*context.font = wordfond;
		context.fillStyle = fillcolor;
		context.strokecolor = strokecolor;
		if(shixin==1)
		{
			context.fillText(wordvalue.value,wordx,wordy);
		}
		if(shixin==2)
		{
			context.strokeText(wordvalue.value,wordx,wordy,width);
		}*/
	}
}

//选择指定的图形
function selectform (e)
{
	var clickX = e.pageX - canvas.offsetLeft;
	var clickY = e.pageY - canvas.offsetTop;

	//判断线段
	for(var i = lines.length-1; i>=0; i--)
	{
		console.log("判断线段过程");
		var mminx;
		var mmaxx;
		var mminy;
		var mmaxy;
		if(lines[i].sx > lines[i].ex)
		{
			mminx = lines[i].ex;
			mmaxx = lines[i].sx;
		}
		else
		{
			mminx = lines[i].sx;
			mmaxx = lines[i].ex;
		}
		if(lines[i].sy > lines[i].ey)
		{
			mminy = lines[i].ey;
			mmaxy = lines[i].sy;
		}
		else
		{
			mminy = lines[i].sy;
			mmaxy = lines[i].ey;
		}
		var kuan = (mmaxx - mminx)/4;
		var gao = (mmaxy - mminy)/4;
		var zhongx = (mmaxx + mminx)/2;
		var zhongy = (mmaxy + mminy)/2;

		if (clickX >= zhongx - kuan && clickX <= zhongx + kuan && clickY >= zhongy - gao && clickY <= zhongy + gao) 
		{
			console.log("选中了线段");
			if (previousSelectedform != null)
				previousSelectedform.isSelected = false;
			previousSelectedform = lines[i];
			lines[i].isSelected = true;
			previousnum = i;
			isDragging = true;
			isDrawing = true;
			shape = 3;
			console.log("选中线段后进行绘制所有图形");
			drawAll();
			return;
		}
	}

	//判断矩形
	for(var i = rectangles.length-1; i>=0; i--)
	{
		console.log("判断矩形过程");
		if (clickX >= rectangles[i].sx && clickX <= rectangles[i].ex && clickY >= rectangles[i].sy && clickY <= rectangles[i].ey) 
		{
			console.log("选中了矩形");
			if (previousSelectedform != null)
				previousSelectedform.isSelected = false;
			previousSelectedform = rectangles[i];
			rectangles[i].isSelected = true;
			previousnum = i;
			isDragging = true;
			isDrawing = true;
			shape = 1;
			console.log("选中矩形后进行绘制所有图形");
			drawAll();
			return;
		}
	}

	//判断圆形
	for(var i = circles.length-1; i>=0; i--)
	{
		console.log("判断圆形过程");
		var distanceFromCenter = Math.sqrt(Math.pow(circles[i].x-clickX,2)+Math.pow(circles[i].y-clickY,2));
		
		if (distanceFromCenter <= circles[i].radius) 
		{
			if (previousSelectedform != null)
				previousSelectedform.isSelected = false;
			previousSelectedform = circles[i];
			circles[i].isSelected = true;
			previousnum = i;
			isDragging = true;
			isDrawing = true;
			shape = 2;
			drawAll();
			return;
		}
	}

	//判断文本
	for(var i = words.length-1; i>=0; i--)
	{
		console.log("判断文本过程");
		console.log("clickX");console.log(clickX);
		console.log("clickY");console.log(clickY);
		console.log("words[i].x");console.log(words[i].x);
		console.log("words[i].y");console.log(words[i].y);

		if (clickX >= words[i].x && clickX <= words[i].x + 130 && clickY <= words[i].y && clickY >= words[i].y - 70) 
		{
			console.log("判断文本成功");
			if (previousSelectedform != null)
				previousSelectedform.isSelected = false;
			previousSelectedform = words[i];
			words[i].isSelected = true;
			previousnum = i;
			isDragging = true;
			isDrawing = true;
			shape = 4;
			drawAll();
			return;
		}
	}
	
}

//拖拽指定图形
function draggingform (e)
{
	//看一个图形是否已经被选中
	if (isDragging == true) 
	{
		if (previousSelectedform != null)
		{
		    //找到当前的鼠标位置
		    var x = e.pageX - canvas.offsetLeft;
		    var y = e.pageY - canvas.offsetTop;

		    //改变选中图形坐标
		    if(shape==2)  //如果是圆形
		    {
		    	previousSelectedform.x = x;
		    	previousSelectedform.y = y;
		    }
		    if(shape==1) //如果是矩形
		    {
		    	var kuan = (previousSelectedform.ex - previousSelectedform.sx)/2;
		    	var gao = (previousSelectedform.ey - previousSelectedform.sy)/2;
		    	previousSelectedform.sx = x - kuan;
		    	previousSelectedform.ex = x + kuan;
		    	previousSelectedform.sy = y - gao;
		    	previousSelectedform.ey = y + gao;
		    }
		    if(shape==3) //如果是线段
		    {
		    	var yidongx = x - (previousSelectedform.sx + previousSelectedform.ex)/2;
		    	var yidongy = y - (previousSelectedform.sy + previousSelectedform.ey)/2;
		    	previousSelectedform.sx = previousSelectedform.sx + yidongx;
		    	previousSelectedform.ex = previousSelectedform.ex + yidongx;
		    	previousSelectedform.sy = previousSelectedform.sy + yidongy;
		    	previousSelectedform.ey = previousSelectedform.ey + yidongy;

		    	/*console.log("yidongx");console.log(yidongx);
		    	console.log("yidongy");console.log(yidongy);

		    	console.log("previousSelectedform.sx");console.log(previousSelectedform.sx);
		    	console.log("previousSelectedform.ex");console.log(previousSelectedform.ex);
		    	console.log("previousSelectedform.sy");console.log(previousSelectedform.sy);
		    	console.log("previousSelectedform.ey");console.log(previousSelectedform.ey);
		    	console.log("previousSelectedform.linecolor");console.log(previousSelectedform.linecolor);
		    	console.log("previousSelectedform.linewidth");console.log(previousSelectedform.linewidth);*/
		    }

		    if(shape==4)  //如果是文本
		    {
		    	previousSelectedform.x = x - 60;
		    	previousSelectedform.y = y + 30;
		    }
		    
		    //重新绘制所有图形
		    isDrawing = true;
		    drawAll();
		}
	}
}

//删除选中的图形
function deleteSelect () 
{
	console.log("进入删除函数");
	//删除选中的元素
	if (previousSelectedform != null)
	{
		if(shape==2)
		{
			circles.splice(previousnum,1);
		}
		if(shape==1)
		{
			rectangles.splice(previousnum,1);
		}
		if(shape==3)
		{
			lines.splice(previousnum,1);
		}
		if(shape==4)
		{
			words.splice(previousnum,1);
		}
		previousnum = 10000; //保证删除一个圆以后不再删除其他的元素
	    //重新绘制所有图形
	    isDrawing = true;
	    drawAll();

	    console.log("删除选中的图形");
	    console.log(circles.length);
	}

}

//用于测试程序输出相关数据
function check()
{
	//console.log("文本信息");console.log(wordvalue.value);
	
	console.log("元素信息");
	console.log("矩形个数");console.log(rectangles.length);
	console.log("圆形个数");console.log(circles.length);
	console.log("线段个数");console.log(lines.length);
	console.log("文本个数");console.log(words.length);

	/*for(var i = lines.length-1; i>=0; i--)
	{
		console.log("线段信息开始");
		console.log("sx");console.log(lines[i].sx);
		console.log("sy");console.log(lines[i].sy);
		console.log("ex");console.log(lines[i].ex);
		console.log("ey");console.log(lines[i].ey);
		console.log("linecolor");console.log(lines[i].linecolor);
		console.log("linewidth");console.log(lines[i].linewidth);
		console.log("线段信息结束");
	}*/
}

//停止拖拽图形
function stopDragging () 
{
	isDragging = false; 
}

//选择图形函数
function select() 
{
	isOkDrawing = false;
	isSelecting = true;

	canvas.onmousedown = selectform;
	canvas.onmousemove = draggingform;
	canvas.onmouseup = stopDragging;
	canvas.onmouseout = stopDragging;

}
//绘制图形函数
function drawok() 
{
	isOkDrawing = true; 
	isSelecting = false;

	canvas.onmousedown = startDrawing;
	canvas.onmouseup = addDrawing;
	canvas.onmouseout = stopDrawing;
	canvas.onmousemove = draw;
}

//改变颜色
function changeColor (color) 
{
	context.strokeStyle = color;
	oldcolor = color;
}
//改变填充色
function changefillColor (color) 
{
	context.fillStyle  = color;
	oldfillcolor = color;
}
//改变画笔粗细
function changeThickness(thickness)
{
	context.lineWidth = thickness;
	oldpathwidth = context.lineWidth;
}
//绘制矩形
function rectangle_f ()
{
	console.log("选择了矩形");
	shape = 1;
}
//绘制圆形
function round_f () 
{
	console.log("选择了圆形");
	shape = 2; 
}
//绘制线段
function segment_f () 
{
	console.log("选择了线段");
	shape = 3;
}
//绘制文本
function word_f()
{
	console.log("选择了文本");
	shape = 4;
}
//选择实心文字
function wordfill()
{
	shixin = 1;
}
//选择空心文字
function wordstroke () 
{
	shixin = 2;
}
//清除屏幕
function clearall () 
{
	context.clearRect(0,0,canvas.width,canvas.height);
	circles = [];
	rectangles = [];
	lines = [];
	words = [];
	num = 0;
}

//撤销操作 采用使用地板颜色覆盖的方式删除
function backdraw () 
{
	context.strokeStyle = '#EEEEEE';
	context.lineWidth = context.lineWidth+5;  //加5，可以在撤销的时候可以去掉临近的不精确导致的画错的线
	if(shape==1) //绘制矩形
	{
		context.beginPath();
		context.rect(startx,starty,endx-startx,endy-starty);
		context.stroke();
		context.closePath();
	}
	else if (shape==2) //绘制圆形
	{
		var radius = Math.sqrt((endx-startx)*(endx-startx)+(endy - starty)*(endy - starty));
		context.beginPath();
		context.arc(startx,starty,radius,0,2*Math.PI);
		context.stroke();
		context.closePath();
	}
	else if (shape==3) //绘制线段
	{
		context.beginPath();
		context.moveTo(startx, starty);
		context.lineTo(endx,endy);
		context.stroke();
		context.closePath();
	}
}

//不知道为什么，行不通
// //绘制图形
// function draw_ok () 
// {
// 	//alert(shape);
// 	if(shape==1) //绘制矩形
// 	{
// 		context.rect(startx,starty,endx,endy);
// 	}
// 	else if (shape==2) //绘制圆形
// 	{
// 		var radius = Math.sqrt((endx-startx)*(endx-startx)+(endy - starty)*(endy - starty));
// 		context.arc(startx,starty,radius,0,2*Math.PI);
// 	}
// 	else if (shape==3) //绘制线段
// 	{
// 		context.lineTo(endx,endy);
// 	}
// }